<?php

class EventController extends FrontEndController
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('uploadUrl', 'create','update', 'uploadAvatar','uploadAvatarImg', 'uploadAvatarPage','updateStatus', 'settingsUrl', 'settingsMember', 
					'viewMembers', 'viewContacts', 'subscribe','deleteUser',
					'urls', 'deleteUrl','createUrls','updateUrl',
					'insertcomment', 'deletecomment', 'insertcommentlike', 'deletecommentlike', 'morecomments'
				),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	
	public function actionCreate()
	{
		$parent = Groups::model()->findByPk($_GET['group']);
		/*if($parent->checkAdmin) 
		{*/
			$model=new Events;		
			if(isset($_POST['Events']))
			{
				$model->attributes=$_POST['Events'];
				//$path = $_SERVER['DOCUMENT_ROOT'].'/upload/events/';
				//$fileName = self::saveImage($model->avatar, $model, $path);
				if($model->save())
				{
					$member = new EventsUsers;
					$member->event_id 	= 	$model->getPrimaryKey();
					$member->user_id  	=	Yii::app()->user->id;
					$member->status 	=	0;
					if($member->save())
					{
						//$this->redirect(array('view','event'=>$model->id));
						$_GET['event'] = $model->getPrimaryKey();
						return $this->actionuploadAvatarPage();
					}					
				}
			}
			$this->render('create',array(
				'model'=>$model,
				'groupName'=>$parent->name,
			));
		/*}
		else 
		{
			$this->redirect(array('groups/view','group'=>$_GET['group']));
		}*/
	}
	
	public function actionUpdate($event)
	{
		$model=$this->loadModel($event);
		if($model->group->checkAdmin) 
		{		
			if(isset($_POST['Events']))
			{
				$model->attributes=$_POST['Events'];
				$path = $_SERVER['DOCUMENT_ROOT'].'/upload/events/';
				$fileName = self::saveImage($model->avatar, $model, $path);
				if($model->save()){
					$this->redirect(array('view','event'=>$model->id));
				}
			}
			$this->render('update',array(
				'model'=>$model,
			));
		}
		else 
		{
			$this->redirect(array('view','event'=>$model->id));
		}
	}

	public function actionSettingsMember($event)
	{
		$model=$this->loadModel($event);
		if($model->group->checkAdmin) 
		{		
			if(isset($_POST['Events']))
			{
				$model->attributes=$_POST['Events'];
				$path = $_SERVER['DOCUMENT_ROOT'].'/upload/events/';
				$fileName = self::saveImage($model->avatar, $model, $path);
				if($model->save()){
					$this->redirect(array('view','event'=>$model->id));
				}
			}
			$this->render('_membersUpdate',array(
				'event'				=>	$model->id,
				'eventName'			=>	$model->name,
				'countSubscribers'	=>	$model->countSubscribers,
				'contacts'		=>	$model->subscribers,
				'Users'	=>	$model->UsersAllUpdate,
			));
		}
		else 
		{
			$this->redirect(array('view','event'=>$model->id));
		}
	}
	public function actionSettingsUrl($event)
	{
		$model=$this->loadModel($event);
		if($model->group->checkAdmin) 
		{		
			if(isset($_POST['Events']))
			{
				$model->attributes=$_POST['Events'];
				$path = $_SERVER['DOCUMENT_ROOT'].'/upload/events/';
				$fileName = self::saveImage($model->avatar, $model, $path);
				if($model->save()){
					$this->redirect(array('view','event'=>$model->id));
				}
			}
			$this->render('_urlsUpdate',array(
				'event'				=>	$model->id,
				'eventName'			=>	$model->name,
				'urls'	=>	$model->urls,
				'countUrls'	=>	$model->countUrls,
			));
		}
		else 
		{
			$this->redirect(array('view','event'=>$model->id));
		}
	}

	public function actionIndex($group)
	{
		$check = Groups::model()->findByPk($group);

		$criteria = new CDbCriteria;
		$criteria->condition 	=	'group_id=:group';
		$criteria->params 	 	=	array(':group'=>$group);
		$criteria->order 		=	'crdate DESC';

		$model = Events::model()->findAll( $criteria );
		$this->render('index',array(
			'model'=>$model,
			'checkAdmin'=>$check->checkAdmin,
			'groupName'=>$check->name,
		));
	}
	
	public function actionView($event)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($event),
		));
	}

	/* Avatar */
	public function actionUploadAvatar()
	{
		$this->renderPartial('uploadAvatar',array(
			'model'=>$this->loadModel($_GET['event'])
		));
	}
	public function actionUploadAvatarPage()
	{
		$this->render('uploadAvatarPage',array(
			'model'=>$this->loadModel($_GET['event'])
		));
	}
	public function actionUploadAvatarImg(){
		$model=new Photos;
		$model->attributes = array('image'=>'');
		$model->album_id = '0';
		$model->user_id = Yii::app()->user->id;
		$model->crdate = date("Y-m-d H:i:s");
		$path = $_SERVER['DOCUMENT_ROOT'].'/upload/events/'.$_GET['event'].'/0/';
		$model->name = self::savePhoto($_FILES['image'], $path);
		$model->save();		

		$avatar_id = $model->getPrimaryKey();
		
		$make = self::loadModel($_GET['event']);
		$make->avatar = $avatar_id;
		$make->save();
		
		echo "{";
		echo				"msg: '" . $avatar_id . "'\n";
		echo "}";
	}
	/* END Avatar */

	public function actionViewMembers($event)
	{
		$this->render('members',array(
				'model'=>$this->loadModel($event),
		));
	}
	public function actionViewContacts($event)
	{
		$this->render('contacts',array(
			'model'=>$this->loadModel($event),
		));
	}
	public function actionSubscribe($event)
	{
		$subscribe = new EventsUsers;
		$subscribe->user_id = Yii::app()->user->id;
		$subscribe->event_id = $event;
		$subscribe->save();
		$this->redirect(array('view','event'=>$event));
	}

	public function actionDeleteUser($id, $event)
	{
		EventsUsers::model()->find(
			'user_id=:userId AND event_id=:event_id',
			array(
				':userId'	=>	$id,
				':event_id'	=>	$event,
			)
		)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			// $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('update', 'id'=>$id));
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : Yii::app()->request->urlReferrer);
	}

	public function actionUrls($event)
	{
		$this->render('urls',array(
			'model'=>$this->loadModel($event),
		));
	}
	public function actionCreateUrls($event)
	{
		$parent = Events::model()->findByPk($event);
		if($parent->group->checkAdmin) 
		{
			if(isset($_POST['EventsUrls']))
			{
				$model = EventsUrls::model()->findByPk($_POST['EventsUrls']['id']);
				$model->attributes=$_POST['EventsUrls'];
				$model->save();
				$this->actionSettingsUrl($event);
			} else {
				$model=new EventsUrls;
				$this->render('_urlsCreate',array(
					'model'		=>	$model,
					'eventName'	=>	$parent->name,
					'event'		=>	$parent->id,
				));
			}
		}
		else 
		{
			$this->redirect(array('event/view','event'=>$event));
		}
	}
	public function actionUploadUrl(){
		$model=new EventsUrls;
	
		if(Yii::app()->request->getParam('event')!=NULL)
		{
			$model->attributes = array('avatar'=>'');
			$path = $_SERVER['DOCUMENT_ROOT'].'/upload/events/'.Yii::app()->request->getParam('event').'/';
	
			$model->name = 'пусто';
			$model->event_id = Yii::app()->request->getParam('group');
			$model->url = 'пусто';
			$model->avatar = self::savePhoto($_FILES['image'], $path);
			$model->save();
			echo "{";
			echo				"msg: '" . $model->id . "'\n";
			echo "}";
		}
	}
	public function actionUpdateUrl($id, $event)
	{
		$parent = Events::model()->findByPk($event);
		if($parent->group->checkAdmin) 
		{
			$model=EventsUrls::model()->findByPk($id);
			if(isset($_POST['EventsUrls']))
			{
				$model->attributes=$_POST['EventsUrls'];
				$path = $_SERVER['DOCUMENT_ROOT'].'/upload/events/'.$event.'/';
				$fileName = self::saveImageUrl($model->avatar, $model, $path);
				if($model->save())
					$this->redirect(array('update', 'event'=>$event));
			}
		
			$this->render('_urlsForm',array(
					'model'=>$model,
					'event'=>$parent->id,
			));
		}
		else 
		{
			$this->redirect(array('event/view','event'=>$event));
		}
	}

	public function actionDeleteUrl($id, $event)
	{
		$model = EventsUrls::model()->findByPk($id);
		if( isset($model->avatar) && $model->avatar != 'noimage.gif' )
		{
			$path = $_SERVER['DOCUMENT_ROOT'].'/upload/events/'.$event.'/';
			if(is_dir($path.$model->avatar)){
				unlink($path.$model->avatar);
			}
		}
		$model->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('settingsUrl', 'event'=>$event));
	}

	// more comments
	public function actionMoreComments(){
		if (Yii::app()->request->isAjaxRequest) {
			if(isset($_GET['event'])){

				$parent_id = (isset($_GET['parent_id'])) ? $_GET['parent_id'] : 0;
				$offset = (isset($_GET['offset'])) ? $_GET['offset'] : 0;
				$limit = (isset($_GET['limit'])) ? $_GET['limit'] : 0;
				
				$comments=EventsComments::model()->findAll(array(
					'order'=> 'id DESC',
					'limit'=> $limit,
					'offset'=> $offset,
					'condition'=>'event_id=:event_id AND parent_id=:parent_id',
					'params'=>array(':event_id'=>$_GET['event'], ':parent_id'=>$parent_id)
				));
				
				$model=$this->loadModel($_GET['event']);
				
				$this->renderPartial('_commentList',array(
					'comments'=>$comments,
					'countComments' => (isset($_GET['countComments'])) ? $_GET['countComments'] : 0,
					'parent_id' => $parent_id,
					'offset' => $offset + $limit,
					'limit' => $limit,
 					'checkAdmin'	=> $model->group->checkAdmin,
					'eventId'  		=>  $model->id,
					'eventAdminId'  =>  $model->group->user_id,
					'eventName'  	=>  $model->name,
					'eventAvatar'   =>  isset($model->avatar_info->name) ? $model->avatar_info->name : 'fuck' 					
				));
			}
		}else{
			$this->redirect(Yii::app()->createUrl('event/view', array('event'=>$_GET['event'])));
		}
	}
	
	
	// add comment
    public function actionInsertComment()
    {
    	if (Yii::app()->request->isAjaxRequest) {
	    	$data = array();
	   
	        if(isset($_POST['text'])){
	        	$data['text'] = $_POST['text'];
	        }else{
	        	$data['text'] = '';
	        } 

	        if(isset($_GET['event'])){
	        	$data['id'] = $_GET['event'];
	        }else{
	        	$data['id'] = 0;
	        }       
	   
	        if(isset($_GET['parent_id'])){
	        	$data['parent_id'] = $_GET['parent_id'];
	        }else{
	        	$data['parent_id'] = 0;
	        }   

	        if(isset($_POST['images'])){
	        	$images = explode(",", $_POST['images']);
	        }else{
	        	$images = 0;
	        }	

	        if(isset($_POST['videos'])){
	        	$videos = explode(",", $_POST['videos']);
	        }else{
	        	$videos = 0;
	        }	        
	        
	        if(isset($_POST['musics'])){
	        	$musics = explode(",", $_POST['musics']);
	        }else{
	        	$musics = 0;
	        }
	        	        
	        if($data['id']){
	        	$make = new EventsComments;
	        	$make->text = $data['text'];
	        	$make->event_id = $data['id'];
	        	$make->user_id = Yii::app()->user->id;
	        	$make->parent_id = $data['parent_id'];
	        	$make->crdate = date("Y-m-d H:i:s");
	       
	        	$make->save();
	        	
	        	$data['comment_id'] =  $make->getPrimaryKey();
	        	
	        	$data['images'] = array();
	        	
	        	if($images){
	        		foreach($images as $image_id){
	        			if($image_id){
	   		     			$make = new EventsCommentsPhotos;
	   		     			$make->event_comment_id = $data['comment_id'];
	   		     			$make->photo_id = $image_id;
	   		     			
	   		     			$make->save();
	   		     			
	   		     			$data['images'][] = Photos::model()->findByPk($image_id);
	        			}
	        		}
	        	}
	        	
	        	$data['videos'] = array();
	        	
	        	if($videos){
	        		foreach($videos as $video_id){
	        			if($video_id){
	        				$make = new EventsCommentsVideos;
	        				$make->event_comment_id = $data['comment_id'];
	        				$make->video_id = $video_id;
	        	
	        				$make->save();
	        	
	        				$data['videos'][] = Video::model()->findByPk($video_id);
	        			}
	        		}
	        	}	 

	        	$data['musics'] = array();
	        	
	        	if($musics){
	        		foreach($musics as $music_id){
	        			if($music_id){
	        				$make = new EventsCommentsMusics;
	        				$make->event_comment_id = $data['comment_id'];
	        				$make->music_user_id = $music_id;
	        				
	        				$make->save();

							$data['musics'][] = MusicUser::model()->findByPk($music_id);
	        			}
	        		}
	        	}	        	
	        	
	        	$user_info = Users::model()->findByPk(Yii::app()->user->id);

	        	$email_to = Events::model()->findByPk( $data['id'] )->group->user;
				if( ($email_to->comment_notification == 1) && ($email_to->last_visit < date("Y-m-d H:i:s", time() - 15*60)) ) 
				{
					Yii::app()->getModule('email');
					$email = new Email;
					$email->from = $user_info->email;
					$email->subject = 'Вчечне';
					$email->layout = 'common';
					$email->type = 'text/html';
					$email->to = $email_to->email;
					$email->view = 'main';
					$email->send(array('header' => 'Новая запись на Вашей стене',
						'content' => $email_to->full_name . ', вы получили новое сообещение от '
							. $user_info->full_name . '<br>'
							. $data['text'] . '<br>'
							. 'Получено ' . Yii::app()->dateFormatter->formatDateTime(date("Y-m-d H:i:s"), 'long','short')
					));
				}
	        	
	        	$data['user'] = array(
	        		'name' => $user_info->full_name,
	        		'id' => $user_info->id,
	        		'avatar' => $user_info->avatar
	        	);

	        	$model=$this->loadModel($data['id']);
	        	
	 			$this->renderPartial('_newComment',array(
					'comment'=>$data,
 					'checkAdmin'	=> $model->group->checkAdmin,
					'eventId'  		=>  $model->id,
					'eventAdminId'  =>  $model->group->user_id,
					'eventName'  	=>  $model->name,
					'eventAvatar'   =>  isset($model->avatar_info->name) ? $model->avatar_info->name : 'fuck' 					
				));
	        }
    	}
    	else
    	{
    		$this->redirect(Yii::app()->createUrl('event/view', array('event'=>$_GET['event'])));
    	}
    }	
	
    
    // delete comment
    public function actionDeleteComment(){
    	if (Yii::app()->request->isAjaxRequest) {
    		if(isset($_GET['comment_id'])){
    			EventsComments::model()->deleteAll("id = '" . $_GET['comment_id'] . "'");
    			EventsComments::model()->deleteAll("parent_id = '" . $_GET['comment_id'] . "'");
    			EventsCommentsLikes::model()->deleteAll	("event_comment_id = '" . $_GET['comment_id'] . "'");    
    			EventsCommentsPhotos::model()->deleteAll("event_comment_id = '" . $_GET['comment_id'] . "'");    
    			EventsCommentsMusics::model()->deleteAll("event_comment_id = '" . $_GET['comment_id'] . "'");
    			EventsCommentsVideos::model()->deleteAll("event_comment_id = '" . $_GET['comment_id'] . "'");
    		} 
    	}else{
    		$this->redirect(Yii::app()->createUrl('event/view', array('event'=>$_GET['event'])));
    	}    	
    }
    
    
     // comment like add
    public function actionInsertCommentLike(){
    	if (Yii::app()->request->isAjaxRequest) {
    		if(isset($_GET['comment_id'])){	
    			$make = new EventsCommentsLikes;
    			$make->event_comment_id = $_GET['comment_id'];
    			$make->user_id = Yii::app()->user->id;
    			
    			$make->save();  

    			$comment_like_id = $make->getPrimaryKey();
    			
    			$data['href_dislike'] = Yii::app()->createUrl('event/deletecommentlike', array('comment_id'=>$_GET['comment_id'], 'comment_like_id'=>$comment_like_id));
    			
    			echo CJSON::encode($data);
    		}
    	}else{
    		$this->redirect(Yii::app()->createUrl('profile/index', array('id'=>Yii::app()->user->id)));
    	}    	
    }
    
    // comment like delete
    public function actionDeleteCommentLike(){
    	if (Yii::app()->request->isAjaxRequest) {
    		if(isset($_GET['comment_like_id'])){
    			EventsCommentsLikes::model()->deleteAll("id = '" . $_GET['comment_like_id'] . "'");
    
    			$data['href_like'] = Yii::app()->createUrl('event/insertcommentlike', array('comment_id'=>$_GET['comment_id']));
    			 
    			echo CJSON::encode($data);
    		}
    	}else{
    		$this->redirect(Yii::app()->createUrl('event/view', array('event'=>$_GET['event'])));
    	}
    }     
  

	// update Status
    public function actionUpdateStatus($event){
    	if (Yii::app()->request->isAjaxRequest) {
    		if(isset($_POST['status'])){
    			$make= $this->loadModel($event);
    			$make->status = $_POST['status'];
    			$make->save();
    		}
    	}else{
    		$this->redirect(Yii::app()->createUrl('event/view', array('event'=>$event)));
    	}
    }  

	public function loadModel($id)
	{
		$model=Events::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
}
